/**
 * 管理后台首页相关JS
 * author: zhanghua 2015-9-9
 */
$(function(){
	login.init();
});

var login = {
	btn  : $('#btnlogin'),
	post : $('#postLoginUrl'),
	jump : $('#jumpUrl'),
	init : function(){
		var that = this;
		that.btn.on('click',function(){
			var data = {
			    username: $('#username').val(),
			    password: $('#password').val()
			};
			if(that.validate(data)){
				that.login(data);
			}
		});
		$(document).keydown(function(event){ 
			if(event.keyCode==13){ 
				that.btn.click(); 
			} 
		});
	},
	validate : function(){
		var messages = {
			required: ':attribute 不能为空.',
			phone   : ':attribute 手机号码格式不正确'
		}
        var rules = {
		    username: 'required|phone',
		    password: 'required',
		};
        var data = {
		    username: $('#username').val(),
		    password: $('#password').val()
		};

        var v = Validator.make(data, rules);
        v.mergeAttribute('username', '用户名');
        v.mergeAttribute('password', '密码');
        v.mergeMessage(messages);
        if(v.fails()) {
        	if(v.messages().username!= null){
        		alert(v.messages().username);
        		return false;
        	}
        	if(v.messages().password!= null){
        		alert(v.messages().password);
        		return false;
        	}
    	}
        if(v.passes()){
        	return true;
        }
	},
	login : function(data){
		this.btn.attr('disabled',true);
		var postUrl = $('#postLoginUrl').val()
		var jumpUrl = $('#jumpUrl').val();
		var jumpPersonalDataUrl = $('#postPersonalDataUrl').val();
		var jumpApplyResultUrl = $('#postApplyResultUrl').val();

		post_json(postUrl, data ,function(res){
			switch(res.status){
				case 1:
					location.href = jumpUrl;
					break;
				case 0:
					alert(res.msg);
					break;
			}
			login.btn.attr('disabled',false);
		});
		return false;
	}
};

